<template>
  <div class="createorder">
    <!-- 顶部Nav区域  -->
    <nav-bar ref="navBar">
      <template v-slot:center>
        <span style="font-size: 0.16rem; color: #fff">订单预览</span>
      </template>
    </nav-bar>
    <!-- 订单默认地址区域 -->
    <div class="order-address" @click="toAddress">
      <div class="order-left">
        <div>
          <span>名字电话: {{ address.name }} {{ address.phone }}</span>
          <span>详细地址信息: {{ address.province }} {{ address.city }} {{ address.county }}</span>
        </div>
      </div>
      <div class="order-right">
        <van-icon name="arrow" />
      </div>
    </div>
    <!-- 商品卡片 -->
    <van-card
      :num="item.num"
      :price="item.goods.price + '.00'"
      desc="描述信息"
      :title="item.goods.title"
      :thumb="item.goods.cover_url"
      v-for="item in cartList"
      :key="item.id"
    />
    <!-- 底部生成订单 -->
    <van-submit-bar :price="totalPrice * 100" button-text="生成订单" @submit="handleCreateOrder">
      <div>商品金额</div>
    </van-submit-bar>
    <!-- 底部弹出层 -->
    <van-action-sheet v-model:show="payIsShow" title="支付订单" @close="payClose">
      <van-grid :border="false" :column-num="2">
        <van-grid-item>
          <p>支付宝二维码</p>
          <van-image :src="aliyun" width="150" height="150" />
        </van-grid-item>
        <van-grid-item>
          <p>微信二维码</p>
          <van-image :src="wechat" width="150" height="150" />
        </van-grid-item>
      </van-grid>
    </van-action-sheet>
  </div>
</template>

<script>
import UseTabBar from 'hooks/tabbar/UseTabBar'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { getOrderPreview, creatOrder, payOrder, payOrderStatus } from 'network/order'
import { Toast, Dialog } from 'vant'
import { reactive, ref, toRefs, onBeforeUnmount } from 'vue'
export default {
  name: 'CreateOrder',
  setup() {
    UseTabBar()
    // 生成store实例
    const store = useStore()
    // 生成路由实例
    const router = useRouter()
    // 订单预览所需要的数据
    const orderState = reactive({
      cartList: [],
      address: {}
    })
    // 订单号
    let orderNum = ref('')
    // 底部弹出层是否展示
    let payIsShow = ref(false)
    // 阿里云二维码
    let aliyun = ref('')
    // 微信二维码
    let wechat = ref('')
    // 定时器
    let timer = null
    // 总价
    let totalPrice = store.state.order.totalPrice
    // 清除定时器
    onBeforeUnmount(() => {
      clearInterval(timer)
    })
    //  初始化事件
    function init() {
      Toast.loading({
        message: '加载中...',
        forbidClick: true
      })
      // 获取订单预览
      getOrderPreview().then(res => {
        if (res.address.length === 0) {
          Toast.clear()
          Dialog.confirm({
            title: '消息',
            message: '您还没有设置收货地址,是否去设置?'
          })
            .then(() => {
              router.push('/address')
            })
            .catch(() => {
              router.go(-1)
            })
        } else {
          if (res.address.filter(item => item.is_default === 1).length) {
            orderState.address = res.address.filter(item => item.is_default === 1)[0]
            orderState.cartList = res.carts
            Toast.clear()
          } else {
            orderState.address = res.address[0]
            orderState.cartList = res.carts
            Toast.clear()
          }
        }
        if (orderState.cartList.length === 0) {
          Toast('当前订单已生成')
          router.push({
            path: '/orderdetail',
            query: {
              id: orderNum.value
            }
          })
        }
      })
    }
    // 初始化执行
    init()

    // 定义一个去地址页面的方法
    function toAddress() {
      router.push('/address')
    }

    // 点击生成订单产生的事件
    const handleCreateOrder = () => {
      const params = {
        address_id: orderState.address.id
      }
      creatOrder(params).then(res => {
        Toast('创建订单成功')
        store.dispatch('cart/updateCart')
        // 订单的Id
        orderNum.value = res.id
        payIsShow.value = true

        payOrder(orderNum.value, { type: 'aliyun' }).then(res => {
          aliyun.value = 'https://api.shop.eduwork.cn' + res.qr_code_url
          wechat.value = 'https://api.shop.eduwork.cn' + res.qr_code_url
        })
        // payOrder(orderNum.value, { type: 'wechat' }).then(res => {
        //   wechat.value = res.qr_code_url
        // })
      })
      // 轮询查看
      timer = setInterval(() => {
        payOrderStatus(orderNum.value).then(res => {
          if (res == '2') {
            clearInterval(timer)
            router.push({
              path: '/orderdetail',
              query: {
                id: orderNum.value
              }
            })
          }
        })
      }, 2000)
    }
    // 底部栏关闭事件
    function payClose() {
      router.push({
        path: '/orderdetail',
        query: {
          id: orderNum.value
        }
      })
    }

    return {
      handleCreateOrder,
      toAddress,
      ...toRefs(orderState),
      totalPrice,
      payIsShow,
      orderNum,
      aliyun,
      wechat,
      payClose
    }
  }
}
</script>

<style lang="scss" scoped>
.createorder {
  .order-address {
    height: 0.72rem;
    padding: 0.16rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
    .order-left {
      height: 100%;
      div {
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        span {
          flex: 1;
        }
      }
    }
    &::before {
      position: absolute;
      right: 0;
      bottom: 0;
      left: 0;
      height: 2px;
      background: repeating-linear-gradient(
        -45deg,
        #ff6c6c 0,
        #ff6c6c 20%,
        transparent 0,
        transparent 25%,
        var(--van-primary-color) 0,
        var(--van-primary-color) 45%,
        transparent 0,
        transparent 50%
      );
      background-size: 80px;
      content: '';
    }
  }
}
.content {
  padding: 0.16rem;
}
::v-deep(.van-card__price) {
  color: red;
}
</style>